package com.iseastar.guojiang.passport;

import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.shouhuobao.station.R;

import java.io.IOException;

import droid.frame.utils.android.VibratorMgr;
import droid.frame.view.ViewPagerExt;

/**
 * Created by joker on 2017/12/23.
 * 火箭侠新任务提醒展示
 */
public class TaskPassportDialogActivity extends BaseActivity2 implements View.OnClickListener, MediaPlayer.OnCompletionListener {

    private BaseFragment mFragment1, mFragment2;
    private ViewPagerExt mViewPager = null;
    private TextView[] mTags = new TextView[2];
    private LinearLayout mPassportTaskTypeLL;//任务类型布局
    private LinearLayout mTopLayoutLL;//顶部布局
    private ImageView mConfirmIV;
    private ServiceTaskBean serviceTaskBean = null;
    private int color;
    private MediaPlayer mediaPlayer = null;
    private PlayerSoundAsync playerSoundAsync = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.in_bottom2top, 0);
        serviceTaskBean = (ServiceTaskBean) getIntent().getSerializableExtra("item");
        super.onCreate(savedInstanceState);
        Window win = getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        // win.getDecorView().setMinimumWidth((int) (win.getWindowManager().getDefaultDisplay().getWidth() * 0.6));// 设置dialog的宽度
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // lp.horizontalMargin = 300;
        lp.gravity = Gravity.CENTER;
        win.setAttributes(lp);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        if (AppLogic.getAppBackgroundPassportList() != null && AppLogic.getAppBackgroundPassportList().size() > 0) {
            for (ServiceTaskBean bean : AppLogic.getAppBackgroundPassportList()) {
                if (bean.getTaskId() == serviceTaskBean.getTaskId()) {
                    playerSoundAsync = new PlayerSoundAsync();
                    playerSoundAsync.execute();
                    AppLogic.getAppBackgroundPassportList().remove(bean);
                    break;
                }
            }
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_task_passport_dialog);
        super.findViewById();
        mPassportTaskTypeLL = (LinearLayout) findViewById(R.id.passport_task_type_ll);
        mTopLayoutLL = (LinearLayout) findViewById(R.id.top_ll);
        mTags[0] = (TextView) findViewById(R.id.task_passport_tab1);
        mTags[0].setOnClickListener(this);
        mTags[1] = (TextView) findViewById(R.id.task_passport_tab2);
        mTags[1].setOnClickListener(this);
        mConfirmIV = (ImageView) findViewById(R.id.confirm_iv);
        mConfirmIV.setOnClickListener(this);
        initFragment();
        mViewPager = (ViewPagerExt) findViewById(R.id.viewpager);
        mViewPager.setSupportScroll(true);
        mViewPager.setFragmentItems(getSupportFragmentManager(), mFragment1, mFragment2);
        mViewPager.setCurrentItem(0, true);
        mViewPager.setOffscreenPageLimit(2);

        if (serviceTaskBean != null) {
            if (Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
                color = Color.parseColor("#F5A623");
            } else {
                color = Color.parseColor("#E72B45");
            }
            mTags[0].setTextColor(color);
            mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    if (position == 0) {
                        mTags[0].setTextColor(color);
                        mTags[1].setTextColor(getResources().getColor(R.color.app_fontcolor_2));
                        mPassportTaskTypeLL.setVisibility(View.VISIBLE);
                    } else {
                        mTags[0].setTextColor(getResources().getColor(R.color.app_fontcolor_2));
                        mTags[1].setTextColor(color);
                        mPassportTaskTypeLL.setVisibility(View.GONE);
                    }
                    mViewPager.setCurrentItem(position);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            TextView newTaskTV = (TextView) findViewById(R.id.new_task_tv);
            if (serviceTaskBean.getNewTaskCnt() == 0) {
                newTaskTV.setVisibility(View.GONE);
            } else {
                newTaskTV.setVisibility(View.VISIBLE);
                if (Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
                    newTaskTV.setTextColor(getResources().getColor(R.color.black_100));
                }
                newTaskTV.setText("（" + serviceTaskBean.getNewTaskCnt() + "）");
            }
            //取消任务
            if (serviceTaskBean.getPassportType() == 1) {
                mTopLayoutLL.setBackgroundResource(R.drawable.courier_cancel_task_top_bg);
                if (Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
                    mConfirmIV.setImageResource(R.drawable.courier_passport_samecity_confirm_icon);
                    findViewById(R.id.passport_task_type_ll).setBackgroundResource(R.drawable.courier_task_cancel_passport_type_bg);
                    ((TextView) findViewById(R.id.passport_task_title_tv)).setText("任务取消通知");
                    ((ImageView) findViewById(R.id.task_icon_iv)).setImageResource(R.drawable.courier_task_samecity_white_icon);
                } else {
                    mConfirmIV.setImageResource(R.drawable.courier_passport_cancel_task_confirm_icon);
                    findViewById(R.id.passport_task_type_ll).setBackgroundResource(R.drawable.courier_task_cancel_passport_type_bg);
                    ((TextView) findViewById(R.id.passport_task_title_tv)).setText("任务取消通知");
                }
            } else {
                if (Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
                    mTopLayoutLL.setBackgroundResource(R.drawable.courier_passport_samecity_top_bg);
                    mConfirmIV.setImageResource(R.drawable.courier_passport_samecity_confirm_icon);
                    findViewById(R.id.passport_task_type_ll).setBackgroundResource(R.drawable.courier_task_passport_samecity_bg);
                    TextView textView = (TextView) findViewById(R.id.passport_task_title_tv);
                    textView.setText("新任务通知");
                    textView.setTextColor(getResources().getColor(R.color.black_100));
                    Drawable drawable = getResources().getDrawable(R.drawable.courier_task_samecity_notice_icon);
                    /// 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    textView.setCompoundDrawables(drawable, null, null, null);
                } else {
                    mTopLayoutLL.setBackgroundResource(R.drawable.courier_new_task_top_bg);
                    mConfirmIV.setImageResource(R.drawable.courier_passport_new_task_confirm_icon);
                    findViewById(R.id.passport_task_type_ll).setBackgroundResource(R.drawable.courier_task_passport_type_bg);
                    ((TextView) findViewById(R.id.passport_task_title_tv)).setText("新任务通知");
                }
            }
            mPassportTaskTypeLL.setVisibility(View.VISIBLE);

            if (Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
                TextView taskTypeTV = (TextView) findViewById(R.id.task_type_tv);
                taskTypeTV.setText("同城直送");
                taskTypeTV.setTextColor(getResources().getColor(R.color.black_100));
                ((ImageView) findViewById(R.id.task_icon_iv)).setImageResource(R.drawable.courier_task_samecity_icon);
            } else {
                //上门
                if (Const.CourierTaskStatus.visitTask == serviceTaskBean.getTaskType()) {
                    ((TextView) findViewById(R.id.task_type_tv)).setText("上门取件");
                    ((ImageView) findViewById(R.id.task_icon_iv)).setImageResource(R.drawable.courier_task_visit_door_icon);
                }
                //驿站揽收
                else if (Const.CourierTaskStatus.stationTask == serviceTaskBean.getTaskType()) {
                    ((TextView) findViewById(R.id.task_type_tv)).setText("驿站揽收");
                    ((ImageView) findViewById(R.id.task_icon_iv)).setImageResource(R.drawable.courier_task_station_icon);
                }
                //快递柜取件
                else if (Const.CourierTaskStatus.cabinetTask == serviceTaskBean.getTaskType()) {
                    ((TextView) findViewById(R.id.task_type_tv)).setText("快递柜取件");
                    ((ImageView) findViewById(R.id.task_icon_iv)).setImageResource(R.drawable.courier_task_cabinet_icon);
                }
            }
        }
    }

    private void initFragment() {
        mFragment1 = new PassportTaskDetailFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putSerializable("item", serviceTaskBean);
        mFragment1.setArguments(bundle1);

        mFragment2 = new PassportTaskMapFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putSerializable("item", serviceTaskBean);
        mFragment2.setArguments(bundle2);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void finish() {
        if (AppLogic.getPassportList() != null && AppLogic.getPassportList().size() > 0) {
            AppLogic.getPassportList().remove(0);
        }
        super.finish();
        overridePendingTransition(0, R.anim.out_top2bottom);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.confirm_iv) {
            finish();
        } else {
            for (int i = 0; i < mTags.length; i++) {
                if (id == mTags[i].getId()) {
                    mViewPager.setCurrentItem(i, true);
                }
            }
        }
    }

    class PlayerSoundAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                AssetFileDescriptor fileDescriptor = null;
                //取消任务
                if (serviceTaskBean.getPassportType() == 1) {
                    fileDescriptor = getApplication().getAssets().openFd("courier_cancel_task.mp3");
                } else {
                    fileDescriptor = getApplication().getAssets().openFd("courier_new_task.mp3");
                }
                if (fileDescriptor == null) {
                    return null;
                }
                mediaPlayer
                        .setDataSource(fileDescriptor.getFileDescriptor(),
                                fileDescriptor.getStartOffset(),
                                fileDescriptor.getLength());
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//STREAM_ALARM
                mediaPlayer.prepare();
                mediaPlayer.setVolume(1.0f, 1.0f);
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            long[] pattern = {100, 400}; // 停止 开启 停止 开启
            VibratorMgr.vibrate(pattern, 0);
            return null;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {// 监听播放器放完
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        VibratorMgr.cancelVibrator();
    }

    @Override
    protected void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        VibratorMgr.cancelVibrator();
        if (playerSoundAsync != null) {
            if (!playerSoundAsync.isCancelled()) {
                playerSoundAsync.cancel(true);
            }
        }
        super.onDestroy();
    }
}
